package com.example.api.mall.logic.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.example.api.mall.config.MinioConfig;
import com.example.api.mall.logic.IFileLogic;
import com.example.common.core.exception.LinkerException;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class FileLogicImpl implements IFileLogic {

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient minioClient;

    @Override
    public String upload(MultipartFile file) {
        if (file.isEmpty()){
            throw new LinkerException("文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        String filePath = "C:/temp/";
        File destFile = new File(filePath +fileName);
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            log.error("文件上传失败：", e);
            throw new LinkerException("文件上传失败");
        }
        //TODO 对接minio接口
        return filePath + fileName;
    }

    @Override
    public List<String> uploads(MultipartFile[] files) {
        List<String> urlList = new ArrayList<>();
        for (MultipartFile file : files){
            urlList.add(this.upload(file));
        }
        return urlList;
    }

    /**
     * 上传到minio
     * minio会给上传的图片生成路径，路径携带很多参数，如果去掉后面的参数浏览器访问时直接进入时就进入了minio的管理界面
     * 是因为访问策略，需要求改bucket的访问策略为可读可写
     * @return
     */
    public String uploadToMinio(MultipartFile file) throws Exception {
        if (null == file){
            return null;
        }
        Date date = DateUtil.date();
        String objectStr = "/" + DateUtil.format(date, "yyyy")
                + "/" + DateUtil.format(date, "MM")
                + "/" + DateUtil.format(date, "dd")
                + "/" + IdUtil.fastSimpleUUID()
                + "_" + file.getOriginalFilename();
        ObjectWriteResponse objectWriteResponse = minioClient.putObject(PutObjectArgs.builder()
                .object(objectStr)
                .bucket(minioConfig.getBucketName())
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(file.getContentType())
                .build());
        return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + objectStr;
    }

}
